package com.xyz.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xyz.pojo.ProductCategory;
import com.xyz.pojo.ProductInfo;
import com.xyz.service.CategoryService;
import com.xyz.service.ProductService;
import com.xyz.utils.ResultVOUtil;
import com.xyz.vo.ProductInfoVO;
import com.xyz.vo.ProductVO;
import com.xyz.vo.ResultVO;

@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

	@Autowired
	private ProductService productInfoService;

	@Autowired
	private CategoryService categoryService;

	@GetMapping("/list")
	public ResultVO list() {

		// 查询所有商家商品
		List<ProductInfo> productInfoList = productInfoService.findUpAll();

		// 查询类目(一次性查询)
		List<Integer> categoryTypeList = new ArrayList<Integer>();
		// 传统方式
		 for (ProductInfo p : productInfoList) {
			 categoryTypeList.add(p.getCategoryType());
		 }
		// lambda
		//productInfoList.stream().map(e -> e.getCategoryType()).collect(Collectors.toList());

		List<ProductCategory> productCategorList = categoryService.findByCategoryTypeIn(categoryTypeList);
		// 数据拼装
		List<ProductVO> productVOList = new ArrayList<>();

		for (ProductCategory productCategory : productCategorList) {
			ProductVO productVO = new ProductVO();
			productVO.setCategoryType(productCategory.getCategoryType());
			productVO.setCategoryName(productCategory.getCategoryName());

			List<ProductInfoVO> productInfoVOList = new ArrayList<>();

			for (ProductInfo productInfo : productInfoList) {

				if (productInfo.getCategoryType().equals(productCategory.getCategoryType())) {
					ProductInfoVO productInfoVO = new ProductInfoVO();
					BeanUtils.copyProperties(productInfo, productInfoVO);

					productInfoVOList.add(productInfoVO);
				}
			}
			productVO.setProductInfoVOList(productInfoVOList);
			productVOList.add(productVO);
		}

		return ResultVOUtil.success(productVOList);
	}

}
